﻿namespace FlexPlatform.DataModel
{
    using System.Collections.ObjectModel;
    using System.Collections.Generic;

    using FlexPlatform.Shared;
    using FlexPlatform.Shared.Validation;
    using FlexPlatform.BusinessLogic;
    
    class Validator : IValidator
    {
        IEnumerable<IValidationRule> clsValidationRules;

        public Validator(IEnumerable<IValidationRule> validationRules)
        {
            clsValidationRules = validationRules;
        }

        /// <summary>
        /// Validates a proposed value.
        /// The validator tries to check all the rules that are attached to the target property.
        /// If one of the rules do not pass, the validation process is stopped.
        /// </summary>
        /// <param name="proposedValue">The value to be checked.</param>
        /// <returns>The list of validation results.</returns>
        public IEnumerable<IValidationResult> Validate(object proposedValue)
        {
            ICollection<IValidationResult> validationResults = new Collection<IValidationResult>();

            foreach (var rule in clsValidationRules)
            {
                var result = rule.Validate(proposedValue);
                if (result != null)
                {
                    validationResults.Add(result);

                    // stop the validation process if this rule caused an Error
                    if (!result.ValidationPassed)
                    {
                        break;
                    }
                }
            }

            return validationResults;
        }
       
    }
}
